﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ZGLXM.ErrorCode;
using ZGLXM.Infra.Interface;
using ZGLXM.Infra.Repository;
using ZGLXM.Writh.Api.Applicantion.Command.Login;
using ZGLXM.Writh.Api.Dtos.Login;

namespace ZGLXM.Writh.Api.Applicantion.Handler.Login
{
    public class LoginCommandHandler:IRequestHandler<LoginCommand, ApiResult>
    {
        private readonly IUserRepository userRepository;
        private readonly IConfiguration configuration;
        private readonly IMapper mapper;
        private readonly ILogger<LoginCommandHandler> logger;
        public LoginCommandHandler(IUserRepository userRepository, IConfiguration configuration, IMapper mapper, ILogger<LoginCommandHandler> logger)
        {
            this.userRepository = userRepository;
            this.configuration = configuration;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var user = await userRepository.GetAsync(x => x.UserName == request.UserName);
            if (user == null)
            {
                logger.LogInformation("用户不存在");
                return ApiResult.Fail("用户不存在");
            }
            if (user.UserPwd != request.UserPwd)
            {
                logger.LogInformation("密码错误");
                return ApiResult.Fail("密码错误");
            }
            var res = mapper.Map<LoginDTO>(user);
            res.Token = GenerateToken(res);
            logger.LogInformation("登录成功");
            return ApiResult.OK(res);
        }



        public string GenerateToken(LoginDTO User)
        {
            var claims = new[]
            {
                new Claim("Sub", User.UserName!),
                new Claim("Jti", User.UserId.ToString())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]!));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
               configuration["Authentication:Issuer"],
               configuration["Authentication:Audience"],
               claims,
               expires: DateTime.Now.AddMinutes(8),
               signingCredentials: creds
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
